<!-- 公司sop配置 -->
<template>
  <div>
    <dt-modal-edit
      ref="info"
      title="后台角色节点设置"
      :label-width="100"
      okText="确定"
      rightText="确定并同步"
      :width="900"
      :showRight="tabName == 0"
      @cancelData="cancelData"
      :loading="loading"
      @ok="onOk()"
      @right="onOk(true)">
      <div class="taskInfo">
        <p>
          <span class="sp1">任务名称：</span>
          <span class="sp2">{{ currentRow.sopName }}</span>
        </p>
      </div>
      <Tabs v-model="tabName" type="card">
        <TabPane label="后台角色" name="0" v-if="currentRow.backRole == 1 || currentRow.backRole == 3">
          <span class="tips">
            <Icon type="md-alert" class="tips_icon" />
            提示：当前“任务责任人”节点中包含后台人员，请设置各业务组织的“任务责任人”。如未设置，则对应节点将不产生扣分
          </span>
          <div class="singInput">
            <Select
              v-model="roleChooseVal"
              style="width: 200px"
              @on-change="roleChange"
              @on-open-change="roleChangeBefore">
              <Option :value="item.roleId" v-for="(item, index) in backRoleList" :key="index">
                {{ item.roleName }}
              </Option>
            </Select>
            <div class="addBtn">
              <Button type="primary" @click="preview">预览设置</Button>
              <Button type="primary" @click="addOrg">添加组织</Button>
              <Button type="primary" @click="ImportSettings">导入设置</Button>
            </div>
          </div>
          <div class="responsiblebox">
            <div class="reposibleTit">
              <span>任务责任人对应组织范围</span>
              <span>任务责任人</span>
              <span>操作</span>
            </div>

            <div class="resposibleCon" v-for="(item, index) in data" :key="item._index">
              <div>
                <tree_select
                  v-model="item.saveOrgIds"
                  ref="areaTree"
                  :treeList="item.companyList"
                  selectPlaceholder="请选择"
                  :maxTagCount="3"
                  :saveAll="true"
                  @onChange="
                    (a, b) => {
                      item.changeFun(item, a, b)
                    }
                  "></tree_select>
              </div>
              <div>
                <!-- <div class="zeBJ">
                <span>{{ `${item.userName}(${item.workNo})` }}</span>
                <span class="zeBJ2" @click="zeBJ2(item,)">编辑</span>
              </div> -->

                <Select
                  v-if="item.zeList && item.zeList.length"
                  v-model="item.userId"
                  style="width: 200px"
                  @on-change="(e) => seChange(e, item)">
                  <Option :value="item.userId" v-for="(item, index) in item.zeList" :key="index">
                    {{ item.userName }}
                  </Option>
                </Select>
                <Select v-else style="width: 200px">
                  <!-- <Option :value="item.userId">Zara AA a </Option> -->
                </Select>
              </div>
              <div @click="delOrg(index)" style="color: #2d8cf0; line-height: 30px; cursor: pointer">
                删除
              </div>
            </div>
          </div>
        </TabPane>
        <TabPane label="指定人员" name="1" v-if="currentRow.backRole == 2 || currentRow.backRole == 3">
          <span class="tips">
            <Icon type="md-alert" class="tips_icon" />
            提示：当前“任务责任人”节点中包含指定人员，请设置对应人员的“SOP积分归属组织”，以确定产生加分或减分时的积分归属
          </span>
          <div class="downBox">
            <div class="specifyTit">
              <span>任务责任人</span>
              <span>角色</span>
              <span>SOP积分归属组织</span>
            </div>
            <div class="specifyConBox">
              <div class="specifyCon" v-for="(item, index) in designatedListVal" :key="index">
                <div>{{ item.userName }}</div>
                <div>
                  <Select
                    v-model="item.roleId"
                    style="width: 200px"
                    @on-change="
                      (e) => {
                        return selChange(e, item)
                      }
                    ">
                    <Option
                      :value="roleItem.key"
                      v-for="(roleItem, roleIndex) in item.roleList"
                      :key="roleIndex">
                      {{ roleItem.value }}
                    </Option>
                  </Select>
                </div>
                <div class="sp1">
                  <Select
                    v-model="item.configOrgType"
                    style="width: 200px"
                    clearable
                    @on-change="attributionValChange(item)">
                    <Option :value="1">人员归属组织</Option>
                    <Option :value="2">人员数据权限归属组织</Option>
                  </Select>
                  <Select v-model="item.orgId" v-if="item.attributionVal2Flag" style="width: 200px">
                    <Option :value="orgItem.key" v-for="(orgItem, orgIndex) in item.orgList" :key="orgIndex">
                      {{ orgItem.value }}
                    </Option>
                  </Select>
                </div>
              </div>
            </div>
          </div>
        </TabPane>
      </Tabs>
      <task-list ref="taskList" @chooseTask="chooseTask"></task-list>

      <back-role-node-set
        ref="backRoleNodeSet"
        @success="backRoleNodeSetSuccess"
        @backClose="backClose"></back-role-node-set>
      <Modal v-model="qieFlag" :footer-hide="true" title="" :closable="false" :mask-closable="false">
        <div class="iconType">
          <Icon type="md-help-circle" size="24" color="#ff9900" />
          “任务责任人对应组织范围”保存提醒
        </div>
        <div style="line-height: 1.8">
          切换角色时，请先对“任务责任人对应组织范围”设置进行保存。如未保存，则已设置的信息将会丢失
        </div>
        <div class="downloadFooter">
          <Button @click="qieCancel">取消</Button>
          <Button type="primary" @click="qieDirectly">直接切换</Button>
          <Button type="primary" @click="qieSave">保存并切换</Button>
        </div>
      </Modal>
    </dt-modal-edit>
    <sync ref="sync"></sync>
  </div>
</template>

<script>
  import businessCommonMgr from '@/biz/businessReport/businessCommon'
  import tree_select from '@/components/tree_select.vue'
  import sopApi from '@/biz/buildingManagement/sopConfig'
  import taskList from './taskList.vue'
  import backRoleNodeSet from './backRoleNodeSet.vue'
  import processApi from '@/biz/flowApproval/processManagement'
  import sync from './responsibleSync.vue'
  export default {
    components: {
      taskList,
      backRoleNodeSet,
      tree_select,
      sync
    },
    data() {
      return {
        companyList: [],
        companyListCopy: [],
        qieFlag: false,
        tabName: '0',
        roleChooseVal: null,
        optVal: null,
        companys: null,
        // 3.8

        currentRow: {},
        data: [],
        tmpData: [],
        backRoleList: [],
        importList: [],
        designatedListVal: [],
        orgListVal: [],
        chooseRoleChooseVal: null,
        originalRoleChooseVal: null,
        loading: false
      }
    },
    created() {
      this.getCompany()
    },
    methods: {
      backClose() {
        this.$refs.taskList.hide()
      },
      async show(data) {
        this.currentRow = data
        this.$refs.info.show()
        await this.getBackRole()
        if (this.currentRow.backRole == 2) {
          this.tabName = '1'
          this.designatedList()
        } else if (this.currentRow.backRole == 1) {
          this.tabName = '0'
          await this.leaderOrgList()
        } else {
          await this.leaderOrgList()
          this.designatedList()
        }
      },
      seChange(e, item) {
        let aa = JSON.parse(JSON.stringify(item))
        console.log(e, item, aa, '4444')
      },
      roleChangeBefore(val) {
        if (val) {
          this.originalRoleChooseVal = this.roleChooseVal
        }
      },
      roleChange(val) {
        this.chooseRoleChooseVal = val
        this.qieFlag = true
      },
      qieCancel() {
        this.roleChooseVal = this.originalRoleChooseVal
        this.qieFlag = false
      },
      qieDirectly() {
        this.leaderOrgList()
        this.qieFlag = false
      },
      qieSave() {
        this.leaderOrgListSave(this.originalRoleChooseVal).then((res) => {
          this.qieFlag = false
          this.leaderOrgList()
        })
      },
      cancelData() {
        this.tabName = '0'
        this.data = []
        this.designatedListVal = []
      },
      backRoleNodeSetSuccess() {
        this.$refs.taskList.hide()
        this.leaderOrgList()
      },
      getBackRole() {
        let params = {
          configId: this.currentRow.id
        }
        return sopApi
          .getBackRole(params)
          .then((res) => {
            if (res && res.length) {
              this.backRoleList = res
              this.roleChooseVal = this.backRoleList[0].roleId
            }
            return res
          })
          .catch(() => {})
      },
      // 任务责任人列表
      getLeader(val) {
        let params = {
          orgIds: val,
          roleId: this.roleChooseVal
        }
        return sopApi
          .getLeader(params)
          .then((res) => {
            res.forEach((item) => {
              item.key = item.userId
              item.value = item.userName
            })
            return res
          })
          .catch(() => {})
      },
      // 获取指定人员的角色
      getRolesByUser(val) {
        let params = {
          userId: val
        }
        return sopApi
          .getRolesByUser(params)
          .then((res) => {
            res.forEach((item) => {
              item.key = item.roleId
              item.value = item.roleName
            })
            return res
          })
          .catch(() => {})
      },
      // 获取指定人员的组织
      getAuthOrgByUser(val) {
        let params = {
          userId: val.userId,
          roleId: val.roleId
        }
        return sopApi
          .getAuthOrgByUser(params)
          .then((res) => {
            res.forEach((item) => {
              item.key = item.orgId
              item.value = item.orgName
            })
            return res
          })
          .catch(() => {})
      },
      selChange(val, e) {
        this.getAuthOrgByUser(e).then((res) => {
          e.orgId = ''
          e.orgList = res
          this.$forceUpdate()
        })
      },
      // 获取指定人员的任务责任人
      designatedList() {
        let params = {
          configId: this.currentRow.id
        }
        sopApi
          .designatedList(params)
          .then((res) => {
            this.designatedListVal = res

            this.designatedListVal.forEach((item) => {
              this.getRolesByUser(item.userId).then((res) => {
                item.roleList = res
                this.$forceUpdate()
              })
              if (item.roleId) {
                this.getAuthOrgByUser(item).then((res) => {
                  item.orgList = res
                  this.$forceUpdate()
                })
              }

              if (item.configOrgType == 2) {
                item.attributionVal2Flag = true
              } else {
                item.attributionVal2Flag = false
              }
            })

            console.log(this.designatedListVal, 'this.designatedListVal')
          })
          .catch(() => {})
      },

      // 责任人获取
      leaderOrgList() {
        let params = {
          configId: this.currentRow.id,
          roleId: this.roleChooseVal
        }
        sopApi
          .leaderOrgList(params)
          .then((res) => {
            let ab = JSON.parse(JSON.stringify(res))
            console.log(res, ab, '获取的数据列表')
            if (res) {
              res.forEach((item, index) => {
                // item.companyIds = item.saveOrgIds
                // item.userId = item.userId
                item._index = 't' + index
                item.companyList = [...this.companyListCopy]
                item.changeFun = (item, a, b) => {
                  let aa = JSON.parse(JSON.stringify(item))
                  console.log(item, aa, '组织更改函数更改前')
                  this.treeSelectHandle(item, a, b)
                }

                // await this.getLeader(item.saveOrgIds).then((res) => {
                //   this.$nextTick(() => {
                //     this.$set(item, 'zeList', res)
                //   })
                // })
              })
              console.log('处理后的数据列表', res)
              this.data = res
            } else {
              this.data = []
            }
          })
          .catch(() => {})
      },

      attributionValChange(val) {
        val.orgId = ''
        if (val.configOrgType == 2) {
          val.attributionVal2Flag = true
        } else {
          val.attributionVal2Flag = false
        }
      },
      getCompany() {
        processApi.getBusinessOrganTree().then((res) => {
          this.companyList = res
          this.companyListCopy = res
        })
        // let params = {
        //   isTwoLevel: true
        // }
        // return businessCommonMgr.getOrganizationTree(params).then((res) => {
        //   this.companyList = res
        // })
      },
      // treeSelectHandle(e, val) {
      //   console.log('1111',e,val)
      //   if (e && e.length) {
      //     this.getLeader(e).then((res) => {
      //       val.zeList = res
      //       let ff = val.zeList.some((item) => {
      //         return item.userId == val.userId
      //       })
      //       if (!ff) {
      //         val.userId = ''
      //       }
      //     })
      //   }
      // },
      delOrg(val) {
        for (let index = 0; index < this.data.length; index++) {
          if (index == val) {
            this.data.splice(index, 1)
          }
        }
      },
      chooseTask(val) {
        if (val.fromSource == 'ImportSettings') {
          this.$refs.backRoleNodeSet.show(
            'ImportSettings',
            this.currentRow,
            this.roleChooseVal,
            val,
            this.backRoleList
          )
        }
      },
      //三个按钮
      preview() {
        this.$refs.backRoleNodeSet.show('preview', this.currentRow, this.roleChooseVal, {}, this.backRoleList)
      },

      treeHandle1(tree) {
        console.log(tree, 'treeeeeeeee')

        tree.forEach((item) => {
          let disFlag = null
          disFlag = item.children.some((child) => {
            return child.disabled == true
          })
          if (disFlag) {
            item.disabled = true
          }
          item.children && this.treeHandle1(item.children)
        })
      },
      // 树disabled
      treeHandle(tree, arr) {
        tree.map((item) => {
          this.$set(item, 'disabled', false)
          if (arr.includes(item.orgId)) {
            item.disabled = true
          }
          item.children && this.treeHandle(item.children, arr)
        })
      },
      allDis(val, arr) {
        let newArr = []
        if (this.data.length) {
          newArr = this.data
            .map((item) => {
              return item.saveOrgIds
            })
            .flat(Infinity)
            .filter((child) => {
              return !arr.includes(child)
            })
          this.treeHandle(val, newArr)
          this.treeHandle1(val)
        }
      },
      addOrg() {
        let len = this.data.length
        this.data.push({
          userId: '',
          userName: '',
          saveOrgIds: [],
          companyList: [...this.companyListCopy],
          zeList: [],
          _index: 't' + len,
          changeFun: (item, a, b) => this.treeSelectHandle(item, a, b)
        })
      },
      treeSelectHandle(item, e, val) {
        let cc = JSON.parse(JSON.stringify(item))
        console.log(item, cc, 'dddddddddddddd')

        this.allDis(val, e)
        if (e && e.length) {
          console.log(item.userId, 'dddddddddddddd11')

          this.getLeader(e).then((res) => {
            // item.zeList = res
            this.$nextTick(() => {
              this.$set(item, 'zeList', res)
              let ff = item.zeList.some((child) => {
                console.log(child.userId, item.userId, '后当 前')
                return child.userId == item.userId
              })
              console.log(ff, 'fffffff')

              if (!ff) {
                item.userId = ''
              }
            })
          })
        }
        console.log('组织更改触发', item, e, val)
      },
      ImportSettings() {
        let params = {
          configId: this.currentRow.id,
          roleId: this.roleChooseVal
        }
        return sopApi
          .importList(params)
          .then((res) => {
            this.importList = res
            this.importList.forEach((item) => {
              item.key = item.id
              item.value = item.sopName
            })
            this.$refs.taskList.show('ImportSettings', this.importList)
          })
          .catch(() => {})
      },

      // 责任人保存
      leaderOrgListSave(roleId) {
        let saveFlag = this.data.some((item) => {
          return item.userId == ''
        })
        let saveFlag1 = this.data.some((item) => {
          return item.saveOrgIds.length < 1
        })
        if (saveFlag || saveFlag1) {
          this.tabName = '0'
          this.$Message.warning('请补全数据')
          return Promise.reject()
        } else {
          let params = {
            configId: this.currentRow.id,
            roleId: roleId ? roleId : this.roleChooseVal,
            userOrgList: this.data
          }
          this.tmpData = this.data
          return sopApi.leaderOrgListSave(params)
        }
      },

      designatedListSave() {
        // // 角色不能为空
        let roFlag = this.designatedListVal.some((item) => {
          return !item.roleId
        })
        let soFlag = this.designatedListVal.some((item) => {
          return !item.configOrgType
        })

        let orFlag = this.designatedListVal.some((item) => {
          return item.attributionVal2Flag && !item.orgId
        })

        if (roFlag || soFlag || orFlag) {
          this.$Message.warning('请补全指定人员内容')
          this.tabName = '1'
          return Promise.reject()
        } else {
          let params = {
            configId: this.currentRow.id,
            list: this.designatedListVal
          }
          return sopApi.designatedListSave(params)
        }
      },

      onOk(sync) {
        this.loading = true
        let noLoading = () => {
          this.loading = false
        }
        let success = () => {
          noLoading()
          this.$refs.info.hide()
          this.$emit('success')
          if (sync) {
            this.$refs.sync.show({
              roleId: this.roleChooseVal,
              userOrgList: this.tmpData
            })
          }
        }
        if (this.currentRow.backRole == 1) {
          this.leaderOrgListSave().then(success, noLoading)
        } else if (this.currentRow.backRole == 2) {
          this.designatedListSave().then(success, noLoading)
        } else if (this.currentRow.backRole == 3) {
          this.leaderOrgListSave().then((res) => {
            this.designatedListSave().then((res) => {
              success()
              this.$Message.success('设置成功')
            }, noLoading)
          }, noLoading)
        }
      }
    }
  }
</script>
<style lang="scss" scoped>
  .taskInfo {
    margin: 10px 0 15px;
  }

  .singInput {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 10px auto;

    .addBtn {
      width: 40%;
      text-align: right;

      > * {
        margin-left: 10px;
      }
    }
  }

  .tips {
    text-align: right;
    line-height: 32px;
    font-size: 14px;
    background: rgba(254, 252, 236, 1);

    .tips_icon {
      font-size: 20px;
      color: #0f42a7;
      vertical-align: sub;
    }
  }

  .downBox {
    border: 1px solid #e8e8e8;
    padding: 20px 20px 202px;
    margin-top: 10px;

    .specifyTit {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      border-bottom: 1px #e8e8e8 solid;
      padding: 0 0 10px;

      > span:first-child {
        width: 15%;
      }

      > span:last-child {
        width: 50%;
      }
      > span:nth-child(2) {
        flex: 1;
      }
    }

    .specifyCon {
      display: flex;
      flex-direction: row;
      justify-content: space-around;
      padding: 10px 0 0;

      > div:first-child {
        width: 15%;
      }

      > div:last-child {
        width: 50%;
      }
      > div:nth-child(2) {
        flex: 1;
      }

      .sp1 {
        display: flex;
        flex-direction: row;

        > * {
          width: 50%;
        }
      }
    }
  }
  .downloadFooter {
    text-align: center;
    border-top: 1px #e8e8e8 solid;
    margin-top: 20px;
    padding: 10px 0;
    > * {
      margin-left: 10px;
    }
    // display: flex;
    // flex-direction: row;
    // justify-content: space-around;
    // width: 80%;
    // margin: 20px auto;
  }
  .iconType {
    font-size: 18px;
    color: #333;
    margin: 10px 0 20px;
  }
  .responsiblebox {
    border: 1px #e8e8e8 solid;
    padding: 20px 20px 202px;
    z-index: 99;
    max-height: 400px;
    overflow-y: auto;
    .reposibleTit {
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      font-weight: bold;
      > span:first-child {
        width: 40%;
      }
      > span:last-child {
        width: 10%;
      }
    }
    .overBox {
      max-height: 400px;
      border: 1px red solid;
      overflow-y: auto;
    }
    .resposibleCon {
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      margin-top: 10px;

      > div:first-child {
        width: 50%;
      }
      > div:last-child {
        width: 20%;
      }
    }
    .zeBJ {
      line-height: 30px;
      .zeBJ2 {
        color: #0f42a7;
        cursor: pointer;
        display: inline-block;
        margin-left: 5px;
      }
    }
  }
</style>
